<template>
  <view class="container">
    <!-- 资产卡片列表 -->
    <z-paging ref="paging" v-model="dataList" @query="queryList">
      <template #top>
        <!-- 顶部筛选栏 -->
        <view class="filter-bar">
          <up-dropdown ref="uDropdownRef">
            <up-dropdown-item
              :title="assetClassification.state.asset_class_name || '资产分类'"
            >
              <view class="slot-content" style="background-color: #ffffff">
                <scroll-view scroll-y="true" style="height: 500rpx">
                  <view
                    v-for="item in assetClassification.list"
                    :key="item.id"
                    class="assets-class"
                    @click="handleFilterClick(item, 'ation')"
                    >{{ item.asset_class_name }}</view
                  >
                </scroll-view>
                <up-button type="primary" @click="handleFilterClear('ation')"
                  >清空</up-button
                >
              </view>
            </up-dropdown-item>
            <up-dropdown-item
              :title="assetLocation.state.asset_address_name || '资产位置'"
            >
              <view class="slot-content" style="background-color: #ffffff">
                <scroll-view scroll-y="true" style="height: 500rpx">
                  <view
                    v-for="item in assetLocation.list"
                    :key="item.id"
                    class="assets-class"
                    @click="handleFilterClick(item, 'location')"
                    >{{ item.asset_address_name }}
                  </view>
                </scroll-view>
                <up-button type="primary" @click="handleFilterClear('location')"
                  >清空</up-button
                >
              </view>
            </up-dropdown-item>
          </up-dropdown>
        </view>
      </template>
      <view class="asset-list">
        <view
          v-for="(item, index) in dataList"
          :key="item.id"
          class="asset-card"
        >
          <!-- 左侧信息 -->
          <view class="asset-right-container">
            <up-image
              :src="getImage(item.image)"
              width="160rpx"
              height="160rpx"
              class="asset-img"
            />
            <view class="status">
              <up-tag :text="item.asset_state_name" size="mini" />
            </view>
          </view>
          <view class="asset-info">
            <view class="asset-name">{{ item.asset_name }}</view>
            <view class="asset-field"
              >使用部门：{{ item.department_name }}</view
            >
            <view class="asset-field">使用人：{{ item.user_name }}</view>
            <view class="asset-field">资产管理员：{{ item.asset_admin_name }}</view>
            <view class="asset-field"
              >资产分类：{{ item.asset_class_name }}</view
            >
            <view class="asset-field">资产编码：{{ item.asset_code }}</view>
            <view class="asset-field">RFID编码：{{ item.label_number }}</view>
          </view>
          <view class="add-btn" @click="addAsset($event, item, index)">
            <u-icon :name="icons(item)" color="#fff"></u-icon>
          </view>
        </view>
      </view>
    </z-paging>

    <!-- 底部栏 -->
    <view class="footer-bar">
      <view class="footer-left" @click="handlePop">
        <l-ball ref="ballRef">
          <u-icon name="grid" size="24" class="footer-icon"></u-icon>
        </l-ball>
        <text class="footer-text">已选资产</text>
      </view>
      <view class="footer-right">
        <text class="footer-count">共计：{{ addedIds.length }}</text>
        <up-button
          :customStyle="{
            width: '200rpx',
            margin: '0',
          }"
          class="confirm-btn"
          type="primary"
          @click="handleSave"
          >确定</up-button
        >
      </view>
    </view>
    <!-- 底部弹出 -->
    <up-popup
      :show="popupShow"
      mode="bottom"
      border-radius="20"
      @close="closePop"
      closeable
    >
      <view
        class="popup-content"
        style="min-height: 200rpx; max-height: 600rpx; overflow-y: auto"
      >
        <view
          v-for="item in addedIds"
          :key="item.id"
          class="asset-card"
          style="background: #f5f5f5"
        >
          <!-- 左侧信息 -->
          <view class="asset-right-container">
            <up-image
              :src="getImage(item.image)"
              width="160rpx"
              height="160rpx"
              class="asset-img"
            />
            <view class="status">
              <up-tag :text="item.asset_state_name" size="mini" />
            </view>
          </view>
          <view class="asset-info">
            <view class="asset-name">{{ item.asset_name }}</view>
            <view class="asset-field"
              >使用部门：{{ item.department_name }}</view
            >
            <view class="asset-field">资产管理员：{{ item.asset_admin_name }}</view>
            <view class="asset-field"
              >资产分类：{{ item.asset_class_name }}</view
            >
            <view class="asset-field">资产编码：{{ item.asset_code }}</view>
            <view class="asset-field">RFID编码：{{ item.label_number }}</view>
          </view>
          <view class="add-btn" @click="handleDelete(item)">
            <u-icon name="minus" color="#fff"></u-icon>
          </view>
        </view>
      </view>
    </up-popup>
  </view>
</template>

<script setup>
import { ref, reactive } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import http, { BASE_URL } from "@/api/request";
import { generateUUID } from "@/utils";

const ballRef = ref(null);
const dataList = ref([]);
const paging = ref(null);
const addedIds = ref([]);
const uDropdownRef = ref(null);
const pageType = ref(""); // 添加页面类型标识

const assetClassification = reactive({
  state: {},
  list: [],
});
const assetLocation = reactive({
  state: {},
  list: [],
});

const enumList = [
  {
    code: "getViewTable",
    name: "getAssetClassList",
  },
  {
    code: "getViewTable",
    name: "getAssetAddressList",
  },
];

onLoad(async (options) => {
  // 获取页面传递的标识
  pageType.value = options.type || "";
  await getFilterList();
});

// 获取枚举

const getFilterList = async () => {
  const batchRequests = enumList
    .map((item) => {
      const params = [
        {
          id: generateUUID(),
          service: "Module",
          method: item.code,
          param: JSON.stringify({
            code: item.name,
            filters: [],
          }),
        },
      ];

      return http.post("/api/module/GetBatchResult", params).then((res) => ({
        ...res,
        name: item.name,
      }));
    })
    .filter(Boolean);

  try {
    const results = await Promise.all(batchRequests);

    results.forEach(({ name, result, isSuccess, code }) => {
      if (!isSuccess || !code) return;
      switch (name) {
        case "getAssetClassList":
          assetClassification.list = result[0].response.data.viewTable;
          break;
        case "getAssetAddressList":
          assetLocation.list = result[0].response.data.viewTable;
          break;
      }
    });
  } catch (error) {
    console.error("获取枚举失败:", error);
  }
};

const queryList = (pageNo, pageSize) => {
  uni.showLoading({
    title: "加载中...",
    mask: true,
  });
  let data = {};
  if (pageType.value === "return") {
    data = {
      code: "getAssetBorrowListByUserId",
      allColumnFilter: true,
      filters: [],
      pageInput: {
        currentPage: pageNo,
        pageSize: pageSize,
      },
      permissionKey: "",
    };
  } else if (pageType.value === 'warranty') {
			data = {
				code: "getAssetList",
				allColumnFilter: true,
				filters: [{
						name: "state",
						value: "IDLE,IN_USE"
					},
					{
						name: "category",
						value: assetClassification.state.asset_class_code || "",
					},
					{
						name: "location",
						value: assetLocation.state.asset_address_code || "",
					},
				],
				pageInput: {
					currentPage: pageNo,
					pageSize: pageSize
				},
				permissionKey: "",
			};
		} else {
    data = {
      code: "getAssetList",
      allColumnFilter: true,
      filters: [
        {
          name: "state",
          value: "IDLE",
        },
        {
          name: "category",
          value: assetClassification.state.asset_class_code || "",
        },
        {
          name: "location",
          value: assetLocation.state.asset_address_code || "",
        },
      ],
      pageInput: {
        currentPage: pageNo,
        pageSize: pageSize,
      },
      permissionKey: "",
    };
  }

  http.post("/api/module/GetViewTable", data).then((res) => {
    if (res.code && res.isSuccess) {
      paging.value.complete(res.result.viewTable);
      uni.hideLoading();
    } else {
      uni.showToast({
        title: res.error,
        duration: 1500,
        icon: "error",
      });
      uni.hideLoading();
    }
  });
};

const getImage = (image) => {
  const type = getItemType(image);
  if (image) {
    if (type === "ID") {
      return `${BASE_URL}/File/GetImage?fileId=${image}`;
    } else {
      return image;
    }
  }
  return "";
};

const getItemType = (item) => {
  const idPattern = /^[a-zA-Z0-9-]+$/; // 包含字母、数字和 - 符号
  const apiPattern = /^\/File\//; // 假设接口地址以 '/File/' 开头
  const pathPattern = /^\/(?!File)/; // 普通路径以 '/' 开头，但不以 '/File/' 开头
  const relativePathPattern = /^[^/]/; // 假设相对路径不以 '/' 开头

  if (idPattern.test(item)) {
    return "ID";
  } else if (apiPattern.test(item)) {
    return "接口"; // 识别接口地址
  } else if (pathPattern.test(item)) {
    return "路径"; // 识别普通路径
  } else if (relativePathPattern.test(item)) {
    return "相对路径"; // 识别相对路径
  } else {
    return "其他";
  }
};

const icons = (item) => {
  return addedIds.value.some((items) => items.id === item.id)
    ? "checkmark"
    : "plus";
};

const handleFilterClick = (item, name) => {
  if (name === "ation") {
    assetClassification.state.asset_class_code = item.asset_class_code;
    assetClassification.state.asset_class_name = item.asset_class_name;
  }
  if (name === "location") {
    assetLocation.state.asset_address_code = item.asset_address_code;
    assetLocation.state.asset_address_name = item.asset_address_name;
  }
  uDropdownRef.value.close();
  if (paging.value) {
    paging.value.reload();
  }
};

const handleFilterClear = (name) => {
  if (name === "ation") {
    assetClassification.state = {};
  }
  if (name === "location") {
    assetLocation.state = {};
  }
  uDropdownRef.value.close();
  if (paging.value) {
    paging.value.reload();
  }
};

const popupShow = ref(false);

const handlePop = (item) => {
  popupShow.value = !popupShow.value;
};
const closePop = () => {
  popupShow.value = !popupShow.value;
};

const handleDelete = (item) => {
  addedIds.value = addedIds.value.filter((items) => item.id !== items.id);
};

const addAsset = (e, item) => {
  if (!ballRef.value) return;
  const id = addedIds.value.some((items) => items.id === item.id);
  if (id) {
    uni.showToast({
      title: "已添加",
      icon: "none",
    });
    return;
  }
  ballRef.value.action(e.detail);
  addedIds.value.push(item);
};

const handleSave = () => {
  if (!addedIds.value.length) {
    uni.showToast({
      title: "请添加资产",
      duration: 1500,
      icon: "error",
    });
    return;
  }
  uni.$emit("assetSelected", addedIds.value);
  uni.navigateBack();
};
</script>

<style lang="scss" scoped>
.container {
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
  min-height: calc(100vh - var(--window-top, 0px));
}

.filter-bar {
  background: #fff;

  .assets-class {
    width: 100%;
    box-sizing: border-box;
    padding: 20rpx;
  }
}

.asset-list,
.popup-content {
  padding: 20rpx;
}

.asset-card {
  position: relative;
  display: flex;
  padding: 24rpx;
  margin-bottom: 24rpx;
  border-radius: 24rpx;
  background: #fff;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);

  .asset-right-container {
    position: relative;

    .status {
      position: absolute;
      right: 0;
      top: 0;
    }
  }

  .asset-info {
    flex: 1;
    margin-left: 24rpx;
    font-size: 28rpx;

    .asset-name {
      font-weight: bold;
      margin-top: 12rpx;
    }

    .asset-field {
      color: #666;
      font-size: 24rpx;
    }
  }

  .add-btn {
    width: 40rpx;
    height: 40rpx;
    background: #ffcc00;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: absolute;
    right: 20rpx;
    bottom: 20rpx;
  }
}

.asset-card:last-child {
  margin-bottom: 0;
}

.footer-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx 30rpx;
  background-color: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

  .footer-left {
    display: flex;
    align-items: center;
    gap: 12rpx;
  }

  .footer-icon {
    margin-right: 4rpx;
  }

  .footer-text {
    font-size: 28rpx;
  }
}

.footer-right {
  display: flex;
  justify-content: center;
  align-items: center;

  .footer-count {
    font-size: 28rpx;
    color: #333;
    margin-right: 20rpx;
  }
}

:deep(.zp-view-super) {
  padding-bottom: 120rpx !important;
}
</style>
